package com.envision.common.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <strong>Title : CommonInterceptor.java<br>
 * </strong> <strong>Description : 登录状态验证</strong><br>
 * <strong>Create on : 2018年03月06日<br>
 * <p>
 *
 * @author karrychang<br>
 * @version <strong>1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人		修改日期		修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class CommonInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies=request.getCookies();
        String global_id;
        boolean flag=false;
        if (cookies != null && cookies.length > 0) {
            //遍历所有Cookie
            for(Cookie cookie: cookies) {
                logger.debug(cookie.getName()+"========"+cookie.getValue());
                //找到name为global_id的Cookie
                if (cookie.getName().equals("global_id")) {
                    global_id = cookie.getValue();
                    String [] str=global_id.split("_");
                    String userLoginMsg=(String )request.getSession().getAttribute(str[0]);
                    flag= str[1].equals(userLoginMsg);
                    logger.debug(flag+"");
                }
            }
        }

        //重定向到登陆页面
        if (!flag){
            String msg="{\"code\":300,\"msg\":\"cookies no effect\",\"data\":null}";
            response.getWriter().print(msg);
//            response.sendRedirect("https://eos.envisioncn.com/hmi/op_login.html");
        }
        return flag;
//        return true;

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}